package com.itheima.tliassystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.itheima.tliassystem.exception.PasswordException;
import com.itheima.tliassystem.exception.UserNameException;
import com.itheima.tliassystem.mapper.EmpMapper;
import com.itheima.tliassystem.service.EmpService;

import entity.Emp;
import entity.EmpQuery;
import entity.PageBen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itheima.tliassystem.uile.BcriptUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    EmpMapper empMapper;

    @Override
    public PageBen pageEmp(EmpQuery empQuery) {

//       Long total  =   empMapper.count();
//       Integer start = (empQuery.getPage()-1)*empQuery.getPageSize();
//       empQuery.setPage(start);
        //开启分页查询
        PageHelper.startPage(empQuery.getPage(), empQuery.getPageSize());
        //查询员工列表
        Page page = (Page) empMapper.pageEmp(empQuery);
        // List<Emp> rows = empMapper.pageEmp(empQuery);

        PageBen pageBen = new PageBen();
//        pageBen.setRows(rows);
//        pageBen.setTotal(total);
        pageBen.setRows(page.getResult());
        pageBen.setTotal(page.getTotal());
        return pageBen;
    }

    @Override
    public void deleteById(List<Integer> ids) {
        empMapper.deleteById(ids);

    }

    @Override
    public void add(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword(BcriptUtils.createPassword("123456"));
        empMapper.add(emp);

    }

    @Override //根据ID查询
    public Emp selectById(Integer id) {
        Emp emp = empMapper.selectById(id);
        return emp;
    }

    @Override
    public void update(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(LocalDateTime.now());
        empMapper.upDate(emp);
    }

    //登录
    @Override
    public Emp checkLongin(Emp emp) {
        Emp emp1 = empMapper.checkLongin(emp.getUsername());
            if (emp1 == null) {
                throw  new UserNameException("用户名不存在");
            }
            if (!BcriptUtils.checkPassword(emp.getPassword(),emp1.getPassword()) ) {
                throw new PasswordException("密码错误");
            }
            return emp1;
        }
    }
